package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 对前端传入的明文密码进行加密操作
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /*
     * 获取当前 ThreadLocal线程下的资源
     * public void set(T value)  设置当前线程局部变量的值
     * public T get()            返回当前线程所对应的线程局部变量的值
     * public void remove()      移除当前线程的线程局部变量
     * */
    //新增员工信息
    @Override
    public void save(EmployeeDTO employeeDTO) {
        //需要转化成实体类----属性名一致的话,进行对象属性拷贝
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);

        //设置账号状态
        employee.setStatus(StatusConstant.ENABLE);

        //设置密码,md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

//        //设定创建时间和修改时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//
//        //设定创建人的id和修改人的id----从request对象中获取jwt标头,得到目前的操作对象,从令牌中解析对象信息
//        long operateUser = BaseContext.getCurrentId();//在BaseContext类中封装了ThreadLocal的static
//        log.info("操作员工:{}", operateUser);
//
//        employee.setCreateUser(operateUser);
//        employee.setUpdateUser(operateUser);

        employeeMapper.save(employee);
    }


    //员工分页查询方法
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        Page<Employee> employeePage = employeeMapper.pageQuery(employeePageQueryDTO);
        PageResult pageResult = new PageResult(employeePage.getTotal(),employeePage.getResult());
        return pageResult;
    }

    //依据id查询员工
    @Override
    public Employee selectById(Long id) {
        return employeeMapper.selectById(id);
    }

    //更改员工status
    @Override
    public void updateStatus(Integer id,Integer status) {
        Employee employee = new Employee();
        employee.setStatus(status);
        employee.setId(Long.valueOf(id));
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
    }

    //更新员工信息
    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
    }

    @Override
    public void updatePasssword(PasswordEditDTO passwordEditDTO) {
        //todo 后续完善密码更新功能
//        Employee employee = new Employee();
//        if(passwordEditDTO.getNewPassword().equals(passwordEditDTO.getOldPassword())){
//            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
//        }
//        if (passwordEditDTO.getOldPassword().equals(employeeMapper.selectById(BaseContext.getCurrentId()).getPassword())){
//            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
//        }
//        employee.setPassword(DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes()));
//        employee.setId(BaseContext.getCurrentId());
//        employeeMapper.update(employee);
    }


}
